package com.kedacom.emptyproject.viewmodel

import android.arch.lifecycle.MutableLiveData
import com.kedacom.emptyproject.model.bean.HttpBaseResult
import com.kedacom.lego.fast.view.LegoFastViewModel
import com.kedacom.lego.fast.view.notice.INotice
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.ConnectException
import java.net.SocketTimeoutException


open class BaseViewModel : LegoFastViewModel() {
    inner class HttpRequestCallback<T> : Callback<HttpBaseResult<T>?> {
        var nLiveData: MutableLiveData<T>? = null

        constructor() {
            showLoading()
        }

        constructor(liveData: MutableLiveData<T>?) {
            showLoading()
            nLiveData = liveData
        }

        override fun onResponse(
            call: Call<HttpBaseResult<T>?>,
            response: Response<HttpBaseResult<T>?>
        ) {
            val baseBean = response.body()
            if (baseBean == null) {
                onFailure(HttpBaseResult.STATUS_FAILURE, "Http Body Is NULL")
                onComplete()
                return
            }
            if (baseBean.isSuccess) {
                onSuccess(baseBean.result)
            } else {
                onFailure(baseBean.status, baseBean.message)
            }
            onComplete()
        }

        override fun onFailure(call: Call<HttpBaseResult<T>?>, t: Throwable) {
            when (t) {
                is ConnectException -> {
                    onFailure(HttpBaseResult.STATUS_NETWORK_UNCONNECTED, "UnConnect Network")
                }
                is SocketTimeoutException -> {
                    onFailure(HttpBaseResult.STATUS_NETWORK_READTIME_OUT, "ReadTime Out")
                }
                else -> {
                    onFailure(HttpBaseResult.STATUS_EXCEPTION, t.message)
                }
            }
            onComplete()
        }

        fun onSuccess(result: T?) {
            nLiveData?.postValue(result)
        }

        fun onFailure(status: Int, message: String?) {
            showToast(message, INotice.TOAST_ERROR)
        }

        fun onComplete() {
            hideLoading()
        }
    }
}
